package com.prj.ufdm.cloud.svr.gateway.config;

import java.nio.charset.Charset;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

@Configuration
public class WebFluxConfig implements WebFluxConfigurer {
	
	/**
	  * 使用 FastJson 
	 * @return
	 */
	@Bean
	public HttpMessageConverters fastJsonHttpMessageConverters() {
		// 打开AutoType功能
		ParserConfig.getGlobalInstance().setAutoTypeSupport(true); 
        // 定义一个转换消息的对象
		FastJsonHttpMessageConverter fastConverter4 = new FastJsonHttpMessageConverter();
		// 配置信息
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
		fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));
        // 媒体类型
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
		// 在转换器中添加配置信息
		fastConverter4.setFastJsonConfig(fastJsonConfig);
		fastConverter4.setSupportedMediaTypes(fastMediaTypes);
		return new HttpMessageConverters(fastConverter4);
	}   
	
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
		RestTemplate  restTemplate= restTemplateBuilder
		           .setConnectTimeout(Duration.ofMillis(15000))
		           .setReadTimeout(Duration.ofMillis(60000))
		           .build();
		return restTemplate;
    }
}
